import React, { useState, useEffect, useRef } from 'react';
import { Card, List, Button, Tag, Typography, Space, message, Spin, Empty, Modal, Tooltip, Divider } from 'antd';
import { 
  BellOutlined, 
  DeleteOutlined,
  CheckOutlined,
  CheckCircleOutlined,
  DeleteFilled,
  ReloadOutlined,
  EyeOutlined,
  ClockCircleOutlined,
  CalendarOutlined,
  TagOutlined
} from '@ant-design/icons';
import { notificationService } from '../services/api';
import { NotificationData } from '../types/api';

const { Title, Text } = Typography;

const Notification: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [notifications, setNotifications] = useState<NotificationData[]>([]);
  const [bulkLoading, setBulkLoading] = useState(false);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [selectedNotification, setSelectedNotification] = useState<NotificationData | null>(null);
  const intervalRef = useRef<NodeJS.Timeout | null>(null);

  // 获取通知列表
  const fetchNotifications = async () => {
    setLoading(true);
    try {
      const response = await notificationService.getNotifications();
      // console.log('通知API响应:', response); // 注释掉以减少控制台输出
      if (response.success && response.data) {
        // console.log('处理后的通知数据:', response.data); // 注释掉以减少控制台输出
        setNotifications(response.data);
      } else {
        console.error('通知API返回失败:', response);
        message.error('获取通知列表失败');
      }
    } catch (error) {
      console.error('获取通知列表异常:', error);
      message.error('获取通知列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 标记通知为已读
  const markAsRead = async (id: number) => {
    try {
      await notificationService.markAsRead(id);
      setNotifications(prev => 
        prev.map(notification => 
          notification.id === id 
            ? { ...notification, is_read: true }
            : notification
        )
      );
      message.success('已标记为已读');
    } catch (error) {
      message.error('标记失败');
    }
  };

  // 删除通知
  const deleteNotification = async (id: number) => {
    try {
      await notificationService.deleteNotification(id);
      setNotifications(prev => prev.filter(notification => notification.id !== id));
      message.success('删除成功');
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 全部标记为已读
  const markAllAsRead = async () => {
    setBulkLoading(true);
    try {
      const response = await notificationService.markAllAsRead();
      if (response.success) {
        setNotifications(prev => 
          prev.map(notification => ({ ...notification, is_read: true }))
        );
        message.success('所有通知已标记为已读');
      }
    } catch (error) {
      message.error('批量标记失败');
    } finally {
      setBulkLoading(false);
    }
  };

  // 全部删除
  const deleteAll = () => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除所有通知吗？此操作不可恢复。',
      okText: '确定',
      cancelText: '取消',
      okType: 'danger',
      onOk: async () => {
        setBulkLoading(true);
        try {
          const response = await notificationService.deleteAll();
          if (response.success) {
            setNotifications([]);
            message.success(response.message || '所有通知已删除');
          }
        } catch (error) {
          message.error('批量删除失败');
        } finally {
          setBulkLoading(false);
        }
      }
    });
  };


  // 查看通知详情
  const viewDetail = async (id: number) => {
    try {
      const response = await notificationService.getNotificationDetail(id);
      if (response.success && response.data) {
        setSelectedNotification(response.data);
        setDetailModalVisible(true);
      } else {
        message.error('获取通知详情失败');
      }
    } catch (error) {
      console.error('获取通知详情异常:', error);
      message.error('获取通知详情失败');
    }
  };

  // 关闭详情模态窗口
  const closeDetailModal = () => {
    setDetailModalVisible(false);
    setSelectedNotification(null);
  };

  // 刷新通知列表
  const refreshNotifications = () => {
    fetchNotifications();
  };


  useEffect(() => {
    fetchNotifications();
    
    // 设置定时刷新（每30秒）
    intervalRef.current = setInterval(() => {
      fetchNotifications();
    }, 30000);

    // 清理定时器
    return () => {
      if (intervalRef.current) {
        clearInterval(intervalRef.current);
      }
    };
  }, []);

  const getTypeColor = (type: string) => {
    const typeColors: { [key: string]: string } = {
      system: 'blue',
      task_reminder: 'orange',
      achievement: 'gold',
      friend_request: 'green',
      message: 'purple',
      schedule: 'cyan',
      success: 'green',
      warning: 'orange',
      error: 'red',
      info: 'blue',
      default: 'default'
    };
    return typeColors[type] || typeColors.default;
  };

  const getTypeText = (type: string) => {
    const typeTexts: { [key: string]: string } = {
      system: '系统通知',
      task_reminder: '任务提醒',
      achievement: '成就解锁',
      friend_request: '好友申请',
      message: '新消息',
      schedule: '日程提醒',
      success: '成功',
      warning: '警告',
      error: '错误',
      info: '信息',
      default: '其他'
    };
    return typeTexts[type] || typeTexts.default;
  };

  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    });
  };


  return (
    <div style={{ padding: '24px' }}>
      <Card>
        <div style={{ marginBottom: '16px' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <Title level={3} style={{ margin: 0 }}>
              <BellOutlined style={{ marginRight: '8px' }} />
              通知中心
            </Title>
            <Space>
              <Tooltip title="刷新通知">
                <Button 
                  icon={<ReloadOutlined />} 
                  onClick={refreshNotifications}
                  loading={loading}
                />
              </Tooltip>
              <Button 
                type="primary" 
                icon={<CheckCircleOutlined />}
                onClick={markAllAsRead}
                loading={bulkLoading}
                disabled={notifications.length === 0 || notifications.every(n => n.is_read)}
              >
                全部已读
              </Button>
              <Button 
                danger 
                icon={<DeleteFilled />}
                onClick={deleteAll}
                loading={bulkLoading}
                disabled={notifications.length === 0}
              >
                全部删除
              </Button>
            </Space>
          </div>
        </div>

        <Spin spinning={loading}>
          {notifications.length === 0 ? (
            <Empty description="暂无通知" />
          ) : (
            <List
              dataSource={notifications}
              renderItem={(notification) => (
                <List.Item
                  actions={[
                    <Button
                      key="detail"
                      type="link"
                      icon={<EyeOutlined />}
                      onClick={() => viewDetail(notification.id)}
                    >
                      查看详情
                    </Button>,
                    !notification.is_read && (
                      <Button
                        key="read"
                        type="link"
                        icon={<CheckOutlined />}
                        onClick={() => markAsRead(notification.id)}
                      >
                        标记已读
                      </Button>
                    ),
                    <Button
                      key="delete"
                      type="link"
                      danger
                      icon={<DeleteOutlined />}
                      onClick={() => deleteNotification(notification.id)}
                    >
                      删除
                    </Button>
                  ]}
                >
                  <List.Item.Meta
                    title={
                      <Space>
                        <Text strong={!notification.is_read}>
                          {notification.title}
                        </Text>
                        <Tag color={getTypeColor(notification.type)} icon={<TagOutlined />}>
                          {getTypeText(notification.type)}
                        </Tag>
                        {!notification.is_read && <Tag color="red">未读</Tag>}
                      </Space>
                    }
                    description={
                      <div>
                        <div style={{ marginBottom: '8px' }}>
                          <Text type="secondary" style={{ fontSize: '12px' }}>
                            <CalendarOutlined style={{ marginRight: '4px' }} />
                            {formatDate(notification.created_at)}
                          </Text>
                        </div>
                        <div style={{ 
                          color: '#666', 
                          fontSize: '14px',
                          lineHeight: '1.4'
                        }}>
                          {notification.summary}
                        </div>
                      </div>
                    }
                  />
                </List.Item>
              )}
            />
          )}
        </Spin>
      </Card>

      {/* 通知详情模态窗口 */}
      <Modal
        title={
          <Space>
            <BellOutlined />
            通知详情
          </Space>
        }
        open={detailModalVisible}
        onCancel={closeDetailModal}
        footer={[
          <Button key="close" onClick={closeDetailModal}>
            关闭
          </Button>
        ]}
        width={600}
                 destroyOnHidden
      >
        {selectedNotification && (
          <div>
            <div style={{ marginBottom: '16px' }}>
              <Title level={4} style={{ marginBottom: '8px' }}>
                {selectedNotification.title}
              </Title>
              <Space>
                <Tag 
                  color={getTypeColor(selectedNotification.type)}
                  icon={<TagOutlined />}
                >
                  {getTypeText(selectedNotification.type)}
                </Tag>
                <Tag color={selectedNotification.is_read ? 'green' : 'red'}>
                  {selectedNotification.is_read ? '已读' : '未读'}
                </Tag>
              </Space>
            </div>

            <Divider />

            <div style={{ marginBottom: '16px' }}>
              <Text type="secondary" style={{ fontSize: '14px' }}>
                <CalendarOutlined style={{ marginRight: '4px' }} />
                创建时间：{formatDate(selectedNotification.created_at)}
              </Text>
            </div>

            <div>
              <Title level={5}>通知内容</Title>
              <div style={{ 
                padding: '12px',
                backgroundColor: '#f5f5f5',
                borderRadius: '6px',
                whiteSpace: 'pre-wrap',
                wordBreak: 'break-word',
                lineHeight: '1.6'
              }}>
                {selectedNotification.content}
              </div>
            </div>

            {selectedNotification.action_url && (
              <div style={{ marginTop: '16px' }}>
                <Button 
                  type="primary" 
                  href={selectedNotification.action_url}
                  target="_blank"
                  rel="noopener noreferrer"
                >
                  查看相关链接
                </Button>
              </div>
            )}

            {selectedNotification.related_id && selectedNotification.related_type && (
              <div style={{ marginTop: '16px' }}>
                <Text type="secondary">
                  关联对象：{selectedNotification.related_type} #{selectedNotification.related_id}
                </Text>
              </div>
            )}
          </div>
        )}
      </Modal>
    </div>
  );
};

export default Notification;